<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>最长公共前缀</title>
  </head>
  <body>
    <script>
      var longestCommonPrefix = function (str) {
        if (str.length == 0) return "";
        let ans = str[0];
        for (let i = 1; i < str.length; i++) {
          let j = 0;
          for (; j < ans.length && j < str[i].length; j++) {
            if (ans[j] != str[i][j]) break;
          }
          ans = ans.substr(0, j);
          if (ans === "") return ans;
        }
        return ans;
      };
      var str = ["dog", "dracecar", "dcar"];
      console.log(longestCommonPrefix(str));
    </script>
  </body>
</html>
